package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.pojo.Dish;
import com.itheima.reggie.pojo.DishFlavor;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {
    @Autowired
    DishFlavorService dishFlavorService;
    @Autowired
    DishMapper dishMapper;

    @Override
    public void saveWithFlavor(DishDto dishDto) {
        this.save(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        flavors.forEach(flavor->flavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public Page<DishDto> pageDish(Integer page, Integer pageSize, String name) {
        Page<DishDto> page1=new Page<>(page,pageSize);
        return dishMapper.pageDish(page1,name);
    }

    @Override
    public void deleteByIds(Long[] ids) {
        List<Dish> list = this.lambdaQuery().in(Dish::getId, ids).eq(Dish::getStatus, 1).list();
        if (list.size()>0){
            throw new CustomerException("有状态启售的菜品，不可删除");
        }
        this.update().in("id",ids).remove();
    }

    @Override
    public DishDto selectWithFlavor(Long id) {
        return dishMapper.selectWithFlavor(id);
    }

    @Override
    public void updateDishWithFlavor(DishDto dishDto) {
        this.updateById(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();
        dishFlavorService.update().eq("dish_id",dishDto.getId()).remove();
        flavors.forEach(flavor->flavor.setDishId(dishDto.getId()));
        dishFlavorService.saveBatch(flavors);
    }

    @Override
    public List<DishDto> listWithFlavor(Long categoryId, String name, Integer status) {
        return dishMapper.listWithFlavor(categoryId,name);
    }

    @Override
    public List<DishDto> getDishBySetmealId(Long setmealId) {
        return dishMapper.getDishBySetmealId(setmealId);
    }
}


